import { _decorator, Label, Sprite } from 'cc';
import { app } from 'db://app-game/core/app';
import { AsyncQueue, NextFunction } from 'db://app-game/libs/collection/AsyncQueue';
import { ecs } from 'db://app-game/libs/ecs/ECS';
import { CCComp } from 'db://app-game/module/common/CCComp';
import { GameEvent } from '../../../../common/config/GameEvent';
import { UIID } from '../../../../common/config/GameUIConfig';
import { smc } from '../../../singleton/SingletonModuleComp';
import { Home } from '../../home/Home';
import { Initialize } from '../Initialize';

const { ccclass, property } = _decorator;
/** 游戏资源加载 */
@ccclass('InitializeViewComp')
@ecs.register('LoadingView', false)
export class InitializeViewComp extends CCComp {
  @property({ type: Label, tooltip: '加载进度条提示文本' })
  promptLabel: Label = null!;
  @property({ type: Sprite, tooltip: '加载进度条' })
  progress: Sprite = null!;
  finished: number = 0;
  total: number = 0;
  loadPaths: { text: string; path: string }[] = [{ text: '正在加载游戏资源...', path: 'images' }];

  protected start(): void {
    let queue: AsyncQueue = new AsyncQueue();
    // 1.注册事件
    this.addEvent();
    // 2.加载资源
    this.loadRes(queue);
    // 3.加载完成事件
    this.onCompleteCallback(queue);
  }

  private addEvent() {
    this.on(GameEvent.LoginSuccess, this.onHandler, this);
  }

  private onHandler(event: string) {
    switch (event) {
      case GameEvent.LoginSuccess:
        // 加载流程结束，移除加载提示界面
        this.ent.remove(InitializeViewComp);
        break;
    }
  }

  /** 加载资源 */
  private async loadRes(queue: AsyncQueue) {
    for (let i = 0; i < this.loadPaths.length; i++) {
      queue.push((next: NextFunction) => {
        const { text, path } = this.loadPaths[i];
        this.progress.fillRange = 0;
        this.promptLabel.string = text;
        app.res.loadDir(path, this.onProgressCallback.bind(this), next);
      });
    }
    // 开始
    queue.play();
  }

  /** 加载进度事件 */
  private onProgressCallback(finished: number, total: number) {
    this.finished = finished;
    this.total = total;

    let progress = finished / total;
    if (progress > this.progress.fillRange) {
      this.progress.fillRange = progress;
    }
  }

  /** 加载完成事件 */
  private onCompleteCallback(queue: AsyncQueue) {
    queue.complete = async () => {
      // 1.切换界面
      if (smc.account.AccountModel.id > -1) {
        this.onHandler(GameEvent.SceneChangeComplete);
      } else {
        // 初始化帐号模块
        smc.account.connect();
      }
    };
  }

  /** 重置 */
  reset(ent: Initialize): void {
    setTimeout(async () => {
      // 关闭加载界面
      app.gui.remove(UIID.Initialize);

      // 打开游戏主界面（自定义逻辑）
      const node = await app.gui.openAsync(UIID.Home);
      const home = ecs.getEntity<Home>(Home);
      if (node) {
        home.jumpCompleted(node);
      }
    }, 500);
  }
}
